package utils;

import java.nio.charset.StandardCharsets;

/**
 * 获取，UTF-8字符串长度
 */
public class UTF8StringLengthUtils {
    public int utf8StringLength(String text){
        int length = 0;

        if (text != null && text.length() >0){
            byte[] byteArr = text.getBytes(StandardCharsets.UTF_8);
            for (int i = 0; i < byteArr.length;){
                byte byteData = byteArr[i];
                //因为Java不支持无符号类型，这里将byte转为int数据
                int data = Byte.toUnsignedInt(byteData);
                //占用1个字节
                if (data <= 0x7F){
                    i += 1;
                }

                //占用2个字节
                if (data >= 0xC0 && data <= 0xDF){
                    i += 2;
                }

                //占用3个字节
                if (data >= 0xE0 && data <= 0xEF){
                    i += 3;
                }

                //占用4个字节
                if (data >= 0xF0 && data <= 0xF7){
                    i += 4;
                }

                //占用5个字节
                if (data >= 0xF8 && data <= 0xFB){
                    i += 5;
                }

                //占用6个字节
                if (data >= 0xFC && data <= 0xFD){
                    i += 6;
                }

                //UTF-8非首字节
                if (data > 0x7F && data < 0xC0){
                    i += 1;
                    continue;
                }

                //长度+1
                length += 1;
            }
        }
        return length;
    }

    public static void main(String[] args) {
        String text = "你好，世界！ cacaca韩文";
        UTF8StringLengthUtils utils = new UTF8StringLengthUtils();
        System.out.println(utils.utf8StringLength(text));
    }
}
